package com.Iconcat.system.controller;


import com.Iconcat.system.entity.CatUser;
import com.Iconcat.system.entity.WithdrawalRecord;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.CatUserService;
import com.Iconcat.system.service.WithdrawalRecordService;
import com.Iconcat.system.util.DateTimeParser;
import com.Iconcat.system.vo.WithdrawalRecordVO;
import com.Iconcat.system.vo.WithdrawalRequestVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zzq
 * @since 2023-12-13
 */
@RestController
@RequestMapping("/system/withdrawal-record")
@CrossOrigin
@Api(value = "用户提现记录模块",tags = "用户提现记录接口")
public class WithdrawalRecordController {
    @Resource
    private WithdrawalRecordService withdrawalRecordService;
    @Resource
    private CatUserService catUserService;

    // 确认通过提现申请
    @PostMapping("/approve-withdrawal/{withdrawalId}")
    public Result approveWithdrawal(@PathVariable Long withdrawalId) {
        try {
            // 根据提现记录ID获取提现记录
            WithdrawalRecord withdrawalRecord = withdrawalRecordService.getById(withdrawalId);

            // 更新提现状态为已通过
            withdrawalRecord.setWithdrawalStatus("已通过");
            withdrawalRecordService.updateById(withdrawalRecord);

            // 扣除用户余额
            Integer userId = withdrawalRecord.getUserId();
            CatUser user = catUserService.getById(userId);
            BigDecimal withdrawalAmount = withdrawalRecord.getWithdrawalAmount();
            BigDecimal balance = user.getWithdrawableBalance();

            if (balance.compareTo(withdrawalAmount) >= 0) {
                user.setWithdrawableBalance(balance.subtract(withdrawalAmount));
                catUserService.updateById(user);
                return Result.ok().message("提现申请已通过，用户余额已扣除");
            } else {
                return Result.error().message("用户余额不足，提现申请通过失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("确认通过提现申请失败");
        }
    }



    // 拒绝提现申请
    @PostMapping("/reject-withdrawal/{withdrawalId}")
    public Result rejectWithdrawal(@PathVariable Long withdrawalId) {
        try {
            // 根据提现记录ID获取提现记录
            WithdrawalRecord withdrawalRecord = withdrawalRecordService.getById(withdrawalId);
            System.out.println(withdrawalRecord);
            // 更新提现状态为已拒绝
            withdrawalRecord.setWithdrawalStatus("已拒绝");
            withdrawalRecordService.updateById(withdrawalRecord);

            // 这里可以添加其他相关逻辑

            return Result.ok().message("提现申请已拒绝");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("拒绝提现申请失败");
        }
    }

    // 查看提现账单信息
    @GetMapping("/withdrawal-bill")
    public Result getWithdrawalBill(
            @RequestParam(required = true, defaultValue = "1") Integer current,
            @RequestParam(required = true, defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchKeyword,
            @RequestParam(required = false) String searchCreateTime,
            @RequestParam(required = false) String searchWithdrawalNumber,
            @RequestParam(required = false) String searchStartTime,
            @RequestParam(required = false) String searchEndTime,
            @RequestParam(required = false) String searchStatus) {
        try {
            Page<WithdrawalRecord> page = new Page<>(current, size);
            LambdaQueryWrapper<WithdrawalRecord> queryWrapper = new LambdaQueryWrapper<>();
            CatUser catUser = new CatUser();
            // 添加条件：如果 searchKeyword 不为空，则添加按照用户账号搜索
            if (StringUtils.isNotBlank(searchKeyword)) {
                queryWrapper.exists("SELECT 1 FROM cat_user cu WHERE cu.userid = user_id AND cu.phone_number LIKE '%" + searchKeyword + "%'");
            }
            // 添加条件：如果 searchWithdrawalNumber 不为空，则添加按照单号搜索
            if (StringUtils.isNotBlank(searchWithdrawalNumber)) {
                queryWrapper.like(WithdrawalRecord::getWithdrawalNumber, searchWithdrawalNumber);
            }

            // 添加条件：如果 searchCreateTime 不为空，则添加按照创建时间搜索
            if (StringUtils.isNotBlank(searchCreateTime)) {
                queryWrapper.eq(WithdrawalRecord::getWithdrawalTime, DateTimeParser.parseTime(searchCreateTime));
            }

//            // 添加条件：如果 searchStartTime 和 searchEndTime 不为空，则添加按照时间范围搜索
            if (StringUtils.isNotBlank(searchStartTime) && StringUtils.isNotBlank(searchEndTime)) {
                queryWrapper.between(WithdrawalRecord::getWithdrawalTime, searchStartTime, searchEndTime);
            }

            // 添加条件：如果 searchStatus 不为空，则添加按照状态搜索
            if (StringUtils.isNotBlank(searchStatus)) {
                queryWrapper.eq(WithdrawalRecord::getWithdrawalStatus, searchStatus);
            }

            IPage<Map<String, Object>> result = withdrawalRecordService.getWithdrawalBillPage(page, queryWrapper);
            return Result.ok().data("list", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("获取提现账单信息失败");
        }
    }

    // 提交提现申请
    @PostMapping("/submit-withdrawal")
    public Result submitWithdrawal(@RequestBody WithdrawalRequestVO withdrawalRequestDTO) {
        try {
            // 根据用户ID检查用户账户余额是否足够，是否满足提现条件
            CatUser user = catUserService.getById(withdrawalRequestDTO.getUserId());
            BigDecimal balance = user.getWithdrawableBalance();
            // 设置提现单号以"wdao"开头
            String withdrawalNumber = "WDAO" + generateUniqueNumber(); // 生成唯一号码的方法，可以根据实际情况修改
            if (balance.compareTo(withdrawalRequestDTO.getWithdrawalAmount()) >= 0) {
                // 创建提现记录
                WithdrawalRecord withdrawalRecord = new WithdrawalRecord();
                withdrawalRecord.setUserId(withdrawalRequestDTO.getUserId());
                withdrawalRecord.setWithdrawalAmount(withdrawalRequestDTO.getWithdrawalAmount());
                withdrawalRecord.setWithdrawalStatus("待审核"); // 初始状态为待审核
                withdrawalRecord.setWithdrawalNumber(withdrawalNumber);
                withdrawalRecordService.save(withdrawalRecord);

                // 这里可以添加其他相关逻辑

                return Result.ok().message("提现申请已提交");
            } else {
                return Result.error().message("用户余额不足，提现申请提交失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("提交提现申请失败");
        }
    }
    // 生成唯一的提现单号
    private String generateUniqueNumber() {
        // 这里可以根据实际情况生成唯一的提现单号，比如使用时间戳、UUID、随机数等
        // 示例：使用时间戳
        return String.valueOf(System.currentTimeMillis());
    }
}

